/**
 * 生物城水世界研学基地 - 主交互脚本
 * 提供页面交互、动画效果、数据管理等功能
 */

// 🌟 全局配置
const CONFIG = {
    animationDuration: 800,
    scrollOffset: 100,
    apiEndpoints: {
        // 预留API接口配置
        feedback: '/api/feedback',
        progress: '/api/progress'
    }
};

// 🎯 主要功能模块
const App = {
    // 初始化应用
    init() {
        this.setupNavigation();
        this.setupScrollEffects();
        this.setupInteractiveElements();
        this.setupProgressTracking();
        this.setupAccessibility();
        this.setupMobileOptimizations();
        
        console.log('🌊 生物城水世界研学基地 - 网站已加载完成！');
    },

    // 🧭 导航栏功能
    setupNavigation() {
        const navbar = document.querySelector('.navbar');
        const navLinks = document.querySelectorAll('.navbar-nav .nav-link');
        
        // 滚动时导航栏效果
        window.addEventListener('scroll', () => {
            if (window.scrollY > 50) {
                navbar.classList.add('navbar-scrolled');
            } else {
                navbar.classList.remove('navbar-scrolled');
            }
        });
        
        // 导航链接点击效果
        navLinks.forEach(link => {
            link.addEventListener('click', (e) => {
                // 移除所有active类
                navLinks.forEach(l => l.classList.remove('active'));
                // 添加active类到当前链接
                link.classList.add('active');
                
                // 移动端关闭菜单
                const navbarCollapse = document.querySelector('.navbar-collapse');
                if (navbarCollapse.classList.contains('show')) {
                    navbarCollapse.classList.remove('show');
                }
            });
        });
        
        // 平滑滚动到锚点
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                e.preventDefault();
                const target = document.querySelector(this.getAttribute('href'));
                if (target) {
                    target.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            });
        });
    },

    // 📜 滚动效果
    setupScrollEffects() {
        // 视差滚动效果
        const parallaxElements = document.querySelectorAll('[data-parallax]');
        
        window.addEventListener('scroll', () => {
            const scrolled = window.pageYOffset;
            
            parallaxElements.forEach(element => {
                const speed = element.dataset.parallax || 0.5;
                const yPos = -(scrolled * speed);
                element.style.transform = `translateY(${yPos}px)`;
            });
        });
        
        // 元素进入视口动画
        const observerOptions = {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        };
        
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('animate-in');
                }
            });
        }, observerOptions);
        
        // 观察所有需要动画的元素
        document.querySelectorAll('.card, .feature-item, .step-item').forEach(el => {
            observer.observe(el);
        });
    },

    // 🎮 交互元素
    setupInteractiveElements() {
        // 功能卡片点击效果
        const featureCards = document.querySelectorAll('.feature-card, .step-card');
        
        featureCards.forEach(card => {
            card.addEventListener('mouseenter', function() {
                this.style.transform = 'translateY(-10px) scale(1.02)';
                this.style.boxShadow = '0 20px 40px rgba(0, 102, 204, 0.2)';
                
                // 添加涟漪效果
                this.style.position = 'relative';
                const ripple = document.createElement('div');
                ripple.className = 'ripple-effect';
                ripple.style.cssText = `
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    width: 0;
                    height: 0;
                    background: rgba(0, 102, 204, 0.1);
                    border-radius: 50%;
                    transform: translate(-50%, -50%);
                    animation: ripple 0.6s ease-out;
                    pointer-events: none;
                `;
                this.appendChild(ripple);
                
                setTimeout(() => ripple.remove(), 600);
            });
            
            card.addEventListener('mouseleave', function() {
                this.style.transform = 'translateY(0) scale(1)';
                this.style.boxShadow = '';
            });
            
            // 点击反馈
            card.addEventListener('click', function() {
                this.style.transform = 'scale(0.95)';
                setTimeout(() => {
                    this.style.transform = 'scale(1)';
                }, 150);
                
                // 播放点击音效（如果支持）
                this.playClickSound?.();
            });
        });
        
        // 按钮点击效果增强
        const buttons = document.querySelectorAll('.btn');
        buttons.forEach(button => {
            button.addEventListener('click', function(e) {
                // 创建点击波纹效果
                const ripple = document.createElement('span');
                const rect = this.getBoundingClientRect();
                const size = Math.max(rect.width, rect.height);
                const x = e.clientX - rect.left - size / 2;
                const y = e.clientY - rect.top - size / 2;
                
                ripple.style.cssText = `
                    position: absolute;
                    width: ${size}px;
                    height: ${size}px;
                    left: ${x}px;
                    top: ${y}px;
                    background: rgba(255, 255, 255, 0.5);
                    border-radius: 50%;
                    transform: scale(0);
                    animation: ripple 0.6s linear;
                    pointer-events: none;
                `;
                
                this.style.position = 'relative';
                this.style.overflow = 'hidden';
                this.appendChild(ripple);
                
                setTimeout(() => ripple.remove(), 600);
            });
        });
        
        // 实验页面特殊交互
        this.setupExperimentInteractions();
    },

    // 🧪 实验页面交互
    setupExperimentInteractions() {
        const experimentCards = document.querySelectorAll('.experiment-card');
        
        experimentCards.forEach(card => {
            // 实验卡片悬停效果
            card.addEventListener('mouseenter', function() {
                const img = this.querySelector('img');
                if (img) {
                    img.style.transform = 'scale(1.1)';
                    img.style.transition = 'transform 0.3s ease';
                }
            });
            
            card.addEventListener('mouseleave', function() {
                const img = this.querySelector('img');
                if (img) {
                    img.style.transform = 'scale(1)';
                }
            });
            
            // 材料清单交互
            const materialLists = card.querySelectorAll('.material-list li');
            materialLists.forEach(item => {
                item.addEventListener('click', function() {
                    this.style.textDecoration = this.style.textDecoration === 'line-through' ? 'none' : 'line-through';
                    this.style.opacity = this.style.textDecoration === 'line-through' ? '0.6' : '1';
                });
            });
        });
        
        // 实验记录表交互
        const recordTable = document.querySelector('.table');
        if (recordTable) {
            const rows = recordTable.querySelectorAll('tbody tr');
            rows.forEach(row => {
                row.addEventListener('click', function() {
                    // 高亮当前行
                    rows.forEach(r => r.style.background = '');
                    this.style.background = '#e3f2fd';
                    
                    // 添加完成动画
                    this.style.animation = 'pulse 0.5s ease-in-out';
                    setTimeout(() => {
                        this.style.animation = '';
                    }, 500);
                });
            });
        }
    },

    // 📊 进度跟踪
    setupProgressTracking() {
        // 检查学习进度
        const progressKey = 'biowater_learning_progress';
        let progress = JSON.parse(localStorage.getItem(progressKey) || '{}');
        
        // 页面访问记录
        const currentPage = window.location.pathname.split('/').pop().replace('.html', '');
        if (!progress.visitedPages) progress.visitedPages = [];
        
        if (!progress.visitedPages.includes(currentPage)) {
            progress.visitedPages.push(currentPage);
            localStorage.setItem(progressKey, JSON.stringify(progress));
            
            // 显示进度提示
            this.showProgressNotification(`🎉 恭喜！你已完成 ${progress.visitedPages.length} 个页面的学习！`);
        }
        
        // 实验完成跟踪
        this.setupExperimentProgress(progress);
    },

    // 🧪 实验进度跟踪
    setupExperimentProgress(progress) {
        const experimentKey = 'biowater_experiments';
        let experiments = JSON.parse(localStorage.getItem(experimentKey) || '{}');
        
        // 为每个实验添加完成按钮（如果存在实验卡片）
        const experimentCards = document.querySelectorAll('.experiment-card');
        
        experimentCards.forEach((card, index) => {
            const experimentId = `experiment_${index + 1}`;
            
            // 添加完成按钮
            const completeBtn = document.createElement('button');
            completeBtn.className = 'btn btn-success btn-sm mt-3';
            completeBtn.innerHTML = '<i class="bi bi-check-circle me-2"></i>完成实验';
            completeBtn.style.cssText = 'transition: all 0.3s ease;';
            
            if (experiments[experimentId]) {
                completeBtn.classList.remove('btn-success');
                completeBtn.classList.add('btn-outline-success');
                completeBtn.innerHTML = '<i class="bi bi-check-circle-fill me-2"></i>已完成';
                completeBtn.disabled = true;
            }
            
            completeBtn.addEventListener('click', function() {
                experiments[experimentId] = {
                    completed: true,
                    completedAt: new Date().toISOString(),
                    experimentName: card.querySelector('h4').textContent
                };
                
                localStorage.setItem(experimentKey, JSON.stringify(experiments));
                
                // 更新按钮状态
                this.classList.remove('btn-success');
                this.classList.add('btn-outline-success');
                this.innerHTML = '<i class="bi bi-check-circle-fill me-2"></i>已完成';
                this.disabled = true;
                
                // 显示庆祝动画
                App.celebrateCompletion();
                App.showProgressNotification('🎉 实验完成！你真棒！');
            });
            
            card.querySelector('.card-body').appendChild(completeBtn);
        });
    },

    // ♿ 无障碍功能
    setupAccessibility() {
        // 键盘导航支持
        document.addEventListener('keydown', (e) => {
            // ESC键关闭模态框/菜单
            if (e.key === 'Escape') {
                const navbarCollapse = document.querySelector('.navbar-collapse.show');
                if (navbarCollapse) {
                    navbarCollapse.classList.remove('show');
                }
            }
            
            // Tab键导航增强
            if (e.key === 'Tab') {
                const focusableElements = document.querySelectorAll(
                    'a, button, input, select, textarea, [tabindex]:not([tabindex="-1"])'
                );
                
                focusableElements.forEach(el => {
                    el.addEventListener('focus', function() {
                        this.style.outline = '2px solid #0066cc';
                        this.style.outlineOffset = '2px';
                    });
                    
                    el.addEventListener('blur', function() {
                        this.style.outline = '';
                        this.style.outlineOffset = '';
                    });
                });
            }
        });
        
        // 屏幕阅读器支持
        const importantElements = document.querySelectorAll('[data-important]');
        importantElements.forEach(el => {
            el.setAttribute('role', 'alert');
            el.setAttribute('aria-live', 'polite');
        });
    },

    // 📱 移动端优化
    setupMobileOptimizations() {
        // 触摸事件优化
        let touchStartY = 0;
        
        document.addEventListener('touchstart', (e) => {
            touchStartY = e.touches[0].clientY;
        });
        
        document.addEventListener('touchmove', (e) => {
            const touchEndY = e.touches[0].clientY;
            const deltaY = touchStartY - touchEndY;
            
            // 防止过度滚动
            if (window.scrollY <= 0 && deltaY < 0) {
                e.preventDefault();
            }
        });
        
        // 移动端菜单优化
        const navbarToggler = document.querySelector('.navbar-toggler');
        if (navbarToggler) {
            navbarToggler.addEventListener('click', function() {
                // 添加触觉反馈（如果支持）
                if ('vibrate' in navigator) {
                    navigator.vibrate(50);
                }
            });
        }
        
        // 图片懒加载
        const images = document.querySelectorAll('img[data-src]');
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.dataset.src;
                    img.classList.remove('lazy');
                    observer.unobserve(img);
                }
            });
        });
        
        images.forEach(img => imageObserver.observe(img));
    },

    // 🎉 完成庆祝动画
    celebrateCompletion() {
        const celebration = document.createElement('div');
        celebration.className = 'celebration-overlay';
        celebration.innerHTML = `
            <div class="celebration-content">
                <div class="celebration-stars">🌟⭐✨🎉🎊</div>
                <h3 class="celebration-text">太棒了！</h3>
                <p class="celebration-subtext">你成功完成了实验！</p>
            </div>
        `;
        
        celebration.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            animation: fadeIn 0.3s ease;
        `;
        
        document.body.appendChild(celebration);
        
        // 添加庆祝动画
        const celebrationContent = celebration.querySelector('.celebration-content');
        celebrationContent.style.cssText = `
            text-align: center;
            color: white;
            animation: bounce 0.6s ease-in-out infinite alternate;
        `;
        
        // 3秒后自动关闭
        setTimeout(() => {
            celebration.style.animation = 'fadeOut 0.3s ease';
            setTimeout(() => celebration.remove(), 300);
        }, 3000);
        
        // 点击关闭
        celebration.addEventListener('click', () => {
            celebration.remove();
        });
    },

    // 📢 进度通知
    showProgressNotification(message) {
        const notification = document.createElement('div');
        notification.className = 'progress-notification';
        notification.textContent = message;
        
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: #28a745;
            color: white;
            padding: 15px 20px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 10000;
            animation: slideInRight 0.3s ease;
            max-width: 300px;
        `;
        
        document.body.appendChild(notification);
        
        // 3秒后自动消失
        setTimeout(() => {
            notification.style.animation = 'slideOutRight 0.3s ease';
            setTimeout(() => notification.remove(), 300);
        }, 3000);
    },

    // 🔊 音效播放（预留）
    playClickSound() {
        // 预留音效播放功能
        // const audio = new Audio('/sounds/click.mp3');
        // audio.play().catch(() => {});
    },

    // 📊 数据收集（预留）
    trackEvent(eventName, data) {
        // 预留数据收集功能
        console.log(`📊 事件追踪: ${eventName}`, data);
        
        // 可以发送到分析服务
        // fetch('/api/analytics', {
        //     method: 'POST',
        //     headers: { 'Content-Type': 'application/json' },
        //     body: JSON.stringify({ event: eventName, data, timestamp: Date.now() })
        // });
    },

    // 🛠️ 工具函数
    utils: {
        // 防抖函数
        debounce(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        },

        // 节流函数
        throttle(func, limit) {
            let inThrottle;
            return function() {
                const args = arguments;
                const context = this;
                if (!inThrottle) {
                    func.apply(context, args);
                    inThrottle = true;
                    setTimeout(() => inThrottle = false, limit);
                }
            };
        },

        // 格式化日期
        formatDate(date) {
            return new Intl.DateTimeFormat('zh-CN', {
                year: 'numeric',
                month: 'long',
                day: 'numeric'
            }).format(date);
        },

        // 生成唯一ID
        generateId() {
            return Date.now().toString(36) + Math.random().toString(36).substr(2);
        }
    }
};

// 🎨 CSS动画样式（动态添加）
const animationsCSS = `
    @keyframes ripple {
        to {
            width: 200px;
            height: 200px;
            opacity: 0;
        }
    }
    
    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }
    
    @keyframes fadeOut {
        from { opacity: 1; }
        to { opacity: 0; }
    }
    
    @keyframes bounce {
        0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
        40% { transform: translateY(-10px); }
        60% { transform: translateY(-5px); }
    }
    
    @keyframes slideInRight {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    
    @keyframes slideOutRight {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
    }
    
    .animate-in {
        animation: fadeIn 0.6s ease-out;
    }
    
    .navbar-scrolled {
        background: rgba(255, 255, 255, 0.95) !important;
        backdrop-filter: blur(10px);
        box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
    }
    
    .celebration-stars {
        font-size: 3rem;
        animation: bounce 1s ease-in-out infinite;
    }
    
    .celebration-text {
        font-size: 2rem;
        margin: 20px 0;
        color: #ffd700;
    }
    
    .celebration-subtext {
        font-size: 1.2rem;
        color: #ffffff;
        opacity: 0.9;
    }
`;

// 添加动画样式到页面
const styleSheet = document.createElement('style');
styleSheet.textContent = animationsCSS;
document.head.appendChild(styleSheet);

// 🚀 应用初始化
document.addEventListener('DOMContentLoaded', () => {
    App.init();
});

// 📱 窗口大小改变时的响应处理
window.addEventListener('resize', App.utils.debounce(() => {
    // 重新计算布局
    App.setupMobileOptimizations();
}, 250));

// 🔄 页面可见性变化处理
document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'visible') {
        // 页面重新可见时的处理
        console.log('📱 页面重新可见，恢复交互');
    } else {
        // 页面隐藏时的处理
        console.log('📱 页面隐藏，暂停非必要功能');
    }
});

// 🎯 导出全局对象供其他脚本使用
window.BioWaterApp = App;